﻿
namespace AuthDemo.Web
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using System.Threading;


    // TODO: Create methods containing your application logic.
    [EnableClientAccess()]
    [RequiresAuthentication ]
    public class MyDomainService : DomainService
    {
        [Invoke]
        public string GetHelloMessage()
        {
            return "Hello";
        }

        private static List<Widget> widgets;

        public override void Initialize(DomainServiceContext context)
        {
            base.Initialize(context);

            if (widgets == null)
            {
                PopulateData();
            }
        }

        private void PopulateData()
        {
            List<string> owners = new List<string>() 
            {
                "owner1","owner2","owner3","owner4"
            };

            widgets = Enumerable.Range(1, 10).Select(i => new Widget
                {
                    Id = i,
                    NickName = "widget"+i,
                    Owner = owners[i%4]
                }).ToList(); ;
        }

        public IQueryable<Widget> GetWidgets()
        {
            return widgets.AsQueryable();
        }

        //[RequiresRole("Admin", ErrorMessage = "You must be a Admin.")]
        [CustomAuthorization(typeof(WidgetAuthorization), "IsWidgetOwner")]
        public void UpdateWidget(Widget widget)
        {
            var existingWidget = widgets.SingleOrDefault(w => w.Id == widget.Id);
            if (existingWidget != null)
            {
                existingWidget.NickName = widget.NickName;
            }
        }
    }

    public class Widget
    {
        [Key]
        public int Id { get; set; }
        public string NickName { get; set; }

        public string Owner { get; set; }
    }
}


